﻿/*
* 作者:haojielyb
* 邮箱:haojielyb@qq.com
*/

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Haojielyb.Swagger2md.Middleware
{
    public class Swagger2mdMiddleware : IMiddleware
    {
        private readonly ISwagger2mdGenerator swaggerDocGenerator;
        private readonly Options opt;

        public Swagger2mdMiddleware([FromServices] ISwagger2mdGenerator swaggerDocGenerator, Options opt)
        {
            this.swaggerDocGenerator = swaggerDocGenerator;
            this.opt = opt;
        }

        public Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            var p = context.Request.Path.Value.Split('/');
            var v = opt.name;

            if (p.Length >= 2)
            {
                if (p[1].ToLower() != opt.path)
                {
                    return next(context);
                }
            }

            if (p.Length == 3)
            {
                v = p[2];
            }
            var stream = swaggerDocGenerator.GetSwagger2mdStreamAsync(v).Result;

            var mime = "application/octet-stream";
            var name = $"Swagger_{v}.md";

            var b = stream.ToArray();
            context.Response.ContentType = mime;
            context.Response.Headers.Add("Content-Disposition", "attachment; filename=" + name);

            return context.Response.Body.WriteAsync(b, 0, b.Length);
        }
    }
}